package window.tab;

import entity.TravelGuideInfo;
import manage.TravelGuideDBManager;
import window.component.ImageSlider;
import window.component.TravelGuideCard;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;

public class HomeTab extends JPanel {
    private JPanel travelGuideListPanel = new JPanel();
    private JScrollPane scrollPane;
    private ArrayList<TravelGuideInfo> travelGuideList;

    public HomeTab() {
        this.setLayout(new BorderLayout());

        travelGuideListPanel.setLayout(new BoxLayout(travelGuideListPanel, BoxLayout.Y_AXIS)); // 先设置布局

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(new ImageSlider(), BorderLayout.NORTH);
        panel.add(travelGuideListPanel, BorderLayout.CENTER);

        scrollPane = new JScrollPane(panel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        this.add(scrollPane);

        loadTravelGuides();
        centerScrollBar();
    }

    public void loadTravelGuides() {
        travelGuideList = TravelGuideDBManager.getAllTravelGuides();
        travelGuideListPanel.removeAll();
        for (TravelGuideInfo travelGuide : travelGuideList) {
            TravelGuideCard card = new TravelGuideCard(travelGuide, this);
            card.setSize(750, 130);
            card.setPreferredSize(new Dimension(750, 130));
            card.setMaximumSize(new Dimension(750, 130));
            travelGuideListPanel.add(card);
        }
        travelGuideListPanel.revalidate(); // 更新面板
        travelGuideListPanel.repaint(); // 重绘面板
        centerScrollBar();
    }

    private void centerScrollBar() {
        SwingUtilities.invokeLater(() -> {
            JScrollBar horizontalScrollBar = scrollPane.getHorizontalScrollBar();
            if (horizontalScrollBar != null) {
                int scrollMiddle = (horizontalScrollBar.getMaximum() - horizontalScrollBar.getVisibleAmount()) / 2;
                horizontalScrollBar.setValue(scrollMiddle);
            }
        });
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Travel Guide Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        HomeTab homeTab = new HomeTab();
        frame.add(homeTab);
        frame.setVisible(true);
    }
}
